package com.cos.lession73_listcontainer.provider;

import com.cos.lession73_listcontainer.ResourceTable;
import com.cos.lession73_listcontainer.entity.Emp;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;
import ohos.agp.render.render3d.ViewHolder;

import java.util.List;

public class EmpItemProvider extends BaseItemProvider {
    public EmpItemProvider(List<Emp> list, AbilitySlice slice) {
        this.list = list;
        this.slice = slice;
    }

    public EmpItemProvider() {
    }

    private List<Emp> list;

    private AbilitySlice slice;

    @Override
    public int getCount() {
        return list != null ? list.size() : 0;
    }

    @Override
    public Object getItem(int i) {
        if (list != null && i >= 0 && i < list.size()) {
            return list.get(i);
        }
        return null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        ViewHolder vm;
        if (component == null) {
            //加载布局对象
            component = LayoutScatter.getInstance(slice)
                    .parse(ResourceTable.Layout_ability_item_emp, null, false);
            vm = new ViewHolder();
            //获取文本对象
            vm.empName = (Text) component.findComponentById(ResourceTable.Id_emp_name);
            vm.empSex = (Text) component.findComponentById(ResourceTable.Id_emp_sex);
            //使用component保存数据
            component.setTag(vm);
        } else {
            vm = (ViewHolder) component.getTag();
        }
        if (vm != null) {
            //操作处理
            //获取数据
            Emp emp = list.get(i);
            //赋值给文本组件的对象
            vm.empName.setText(emp.getEname());
            vm.empSex.setText(emp.getEsex());
        }
        //返回component对象
        return component;
    }

    static class ViewHolder{
        Text empName=null;
        Text empSex=null;
    }

}
